<?php
declare(strict_types=1);
namespace app\helper;
use app\model\SystemLog;

/**
 * process进程锁
 * @class ProcessLockHelper
 */
class ProcessLockHelper
{
    /**
     * 所有锁文件地址
     * @var string
     */
    private $lock = [
        'pieceshash' => 'public/lock/ph.lock', // 定时更新种子库任务
        'reseed' => 'public/lock/reseed.lock', // 辅种任务
    ];
    private $lockFile;

    public function __construct($type = 0)
    {
        switch ($type) {
            case 0:
                break;
            case 1:
                $this->lockFile = $this->lock['pieceshash'];
                break;
            case 2:
                $this->lockFile = $this->lock['reseed'];
                break;
        }

    }
    // 检查锁文件是否存在  
    function isLockExists()
    {
        return file_exists($this->lockFile);
    }

    // 创建锁文件  
    function createLock()
    {
        $handle = fopen($this->lockFile, 'w');
        fclose($handle);
    }

    // 删除锁文件  
    function removeLock()
    {
        if (file_exists($this->lockFile)) {  
            if (!unlink($this->lockFile)) {  
                $log = new SystemLog();
                $log->save(['type'=>'error','msg'=> "无法删除锁文件: {$this->lockFile}"]);
            }  
        }  
    }
}
